/**
 * Copyright 2014 @ z3q.net.
 * name :
 * author : jarryliu
 * date : 2013-11-25 21:43
 * description :
 * history :
 */

package member

import (
    //"time"
	"errors"
	"strings"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
)

// 会员收货地址
type DeliverAddr struct {
	AddressId  int64    `orm:"column(address_id);pk;auto" json:"address_id" form:"address_id"`  /*地址编号*/
	MemberId   int64    `orm:"column(member_id);index" json:"member_id" form:"member_id"`
	Country    string   `orm:"column(country);null" json:"country" form:"country"`          /*国家*/
	Province   string   `orm:"column(province);null" json:"province" form:"province"`       /* 省 */
	City       string   `orm:"column(city);null" json:"city" form:"city"`                   /* 市 */
	District   string   `orm:"column(district);null" json:"district" form:"district"`       /*地区信息，例：天津 天津市 红桥区*/
	Address    string   `orm:"column(address);size(256);null" json:"address" form:"address"` /*地址信息，例：水游城8层*/
	Email      string   `orm:"column(email);size(256);null" json:"email" form:"email"`       /*email*/
	CityId     int      `orm:"column(city_id)" json:"city_id" form:"city_id"`                /*城市编号(地址联动的第二级)  */
	DistrictId int      `orm:"column(district_id)" json:"district_id" form:"district_id"`    /* 地区编号(地址联动的第三级) */
	PostCode   string   `orm:"column(post_code);null" json:"post_code" form:"post_code"`     /*邮编*/
	Longitude  float64  `orm:"column(longitude)" json:"longitude" form:"longitude"`          // 经度,范围为-180~180,负数表示西经
	Latitude   float64  `orm:"column(latitude)" json:"latitude" form:"latitude"`             // 维度,范围为-90~90,负数表示南纬
	RealName   string   `orm:"column(real_name)" json:"real_name" form:"real_name"`          /* 姓名 */
    Phone      string   `orm:"column(phone);size(128);null" json:"phone" form:"phone"`       /* 电话号码 */
    Mobile     string   `orm:"column(mobile);size(128);null" json:"mobile" form:"mobile"`    /*手机  */	
    IsDefault  int      `orm:"column(is_default)" json:"is_default" form:"is_default"`       /*  */	
}

func init() {
    orm.RegisterModel(new(DeliverAddr))   
}

// 创建地址
func AddDeliver(v *DeliverAddr) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(v)
	return
}

func GetDeliverAddrById(id int64) (v *DeliverAddr, err error) {
	o := models.GetDefaultDB()
	v = &DeliverAddr{AddressId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAddrByMemberId(memberId int64) (addr *DeliverAddr, err error) {
	o := models.GetDefaultDB()
	addr = &DeliverAddr{MemberId:memberId}   //多个的话,read中需要指明列
	if err = o.Read(addr,"MemberId"); err != nil {
		return addr, err
	}
	return addr, nil
}

func GetDefaultAddrByMemberId(memberId int64) (addr *DeliverAddr, err error) {
	o := models.GetDefaultDB()
	addr = &DeliverAddr{MemberId:memberId,IsDefault:1}   //多个的话,read中需要指明列
	if err = o.Read(addr,"MemberId", "IsDefault"); err != nil {
		return addr, err
	}
	return addr, nil
}

// 获取配送地址列表
func GetAllDeliverAddr(memberId int64)(lists []*DeliverAddr, err error){
	o := models.GetDefaultDB()
	_, err = o.QueryTable(new(DeliverAddr)).Filter("member_id", memberId).OrderBy("-address_id").All(&lists)
	return
}

func GetAllDeliverAddrs(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*DeliverAddr,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(DeliverAddr))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*DeliverAddr
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

// 更新地址
func UpdateDeliver(v *DeliverAddr,param ...string) (id int64, err error) {
	o := models.GetDefaultDB()
	m := DeliverAddr{AddressId: v.AddressId}
	if err = o.Read(&m); err == nil {
		if id, err = o.Update(v, param...); err == nil {
		    return
		}
	}
	return
}

// 删除配送地址
func DeleteDeliver(deliverId int64) (err error) {
	o := models.GetDefaultDB()
	v := DeliverAddr{AddressId: deliverId}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return
		}
	}
	return
}
